//
//  RecommendViewController.m
//  Double
//
//  Created by 孟令博 on 15/5/21.
//  Copyright (c) 2015年 孟令博. All rights reserved.
//

#import "RecommendViewController.h"
#import <AFNetworking/AFNetworking.h>
#import "SubjectViewController.h"
#import <UIImageView+WebCache.h>
#import "RecommendModel.h"
#import "CartoonRecommendCell.h"
#import "CartoonRecommendDetailViewController.h"
#import "CartoonActivityViewController.h"
#import "MJRefresh.h"
#import "Reachability.h"


@interface RecommendViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, retain) NSMutableArray *tableArray;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, assign) int i;


@end

@implementation RecommendViewController
- (void)dealloc
{
    [_tableArray release];
    [_tableView release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableArray = [NSMutableArray array];
        self.i = 2;
    }
    return self;
}

- (void)loadView
{
    [super loadView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkNetwork];
//    [self startConnection];
//    [self createTableView];
}

#pragma mark -
#pragma mark 检测网络
- (void)checkNetwork
{
    //网络请求的判断
    Reachability *reach = [Reachability reachabilityWithHostName:@"http://www.baidu.com"];
    //获取当前网络状态
    NetworkStatus  state = [reach currentReachabilityStatus];
    
    switch (state) {
        case NotReachable:
            NSLog(@"网络连接失败");
            NSString *str = @"网络连接失败";
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
            [alert release];
            break;
        case ReachableViaWiFi:
            NSLog(@"WiFi连接");
            UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"WiFi连接" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert1 show];
            [alert1 release];
            [self startConnection];
            [self createTableView];
            break;
        case ReachableViaWWAN:
            NSLog(@"3G连接");
            
            UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"3G连接" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert2 show];
            [alert2 release];
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark 数据请求
- (void)startConnection
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str = [NSString stringWithFormat:@"http://manhua.haomee.cn/?m=Cartoon&ios=23&pad=0&a=newIndex&tab=1&page=1&limit=15&hasTopic=1"];
                     
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = [dic objectForKey:@"list"];
        for (NSDictionary *dic in array) {
            RecommendModel *model = [[RecommendModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            if ([model.goToType isEqualToString:@"0"]) {
                
                [self.tableArray addObject:model];
            }
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

#pragma mark -
#pragma mark 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 110) style:UITableViewStylePlain];
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 200;
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.view addSubview:self.tableView];
}

#pragma mark -
#pragma mark 下拉刷新
- (void)loadNewData
{
    [self.tableArray removeAllObjects];
    [self startConnection];
    [self.tableView reloadData];
    [self.tableView.header endRefreshing];
}

#pragma mark -
#pragma mark 上拉加载
- (void)loadMoreData
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *str = [NSString stringWithFormat:@"http://manhua.haomee.cn/?m=Cartoon&ios=23&pad=0&a=newIndex&tab=1&page=%d&limit=15&hasTopic=1", self.i];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = [dic objectForKey:@"list"];
        if (array.count == 0) {
            [self.tableView removeFooter];
            return ;
        }
        for (NSDictionary *dic in array) {
            RecommendModel *model = [[RecommendModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            if ([model.goToType isEqualToString:@"0"]) {
                
                [self.tableArray addObject:model];
            }
        }
         self.i += 1;
        [self.tableView.footer endRefreshing];
        [self.tableView reloadData];
        NSLog(@"第%d页", self.i);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.tableView.footer endRefreshing];
    }];
    

}


#pragma mark -
#pragma mark 实现cell方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    static NSString *cellIdentifier = @"cell";
    CartoonRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[CartoonRecommendCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    
    
    CATransform3D rotation;
    rotation = CATransform3DMakeRotation( (20.0*M_PI)/180, 0.0, 0.7, 0.4);
    rotation.m33 = 0.1;
    
    cell.layer.shadowColor = [[UIColor blackColor]CGColor];
    cell.layer.shadowOffset = CGSizeMake(10, 10);
    cell.alpha = 0;
    cell.layer.transform = rotation;
    cell.layer.anchorPoint = CGPointMake(0, 0.5);
    
    
    [UIView beginAnimations:@"rotation" context:NULL];
    [UIView setAnimationDuration:1];
    cell.layer.transform = CATransform3DIdentity;
    cell.alpha = 0.5;
    cell.layer.shadowOffset = CGSizeMake(0, 0);
    [UIView commitAnimations];
    
    
    RecommendModel *model = [self.tableArray objectAtIndex:indexPath.row];
    if ([model.goToType isEqualToString:@"0"]) {
        
        [cell.showImage sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"] options:SDWebImageRetryFailed];
        cell.nameLabel.text = model.name;
        cell.lastupLabel.text = model.lastup;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        RecommendModel *model = [self.tableArray objectAtIndex:indexPath.row];
    if ([model.goToType isEqualToString:@"1"]) {
        
        CartoonActivityViewController *activity = [[CartoonActivityViewController alloc] init];
        activity.picUrl = model.myId;
        [self.navigationController pushViewController:activity animated:YES];
    }
     else {
        RecommendModel *model = [self.tableArray objectAtIndex:indexPath.row];
    CartoonRecommendDetailViewController *detail = [[CartoonRecommendDetailViewController alloc] init];
    detail.iD = model.myId;
    detail.lastup = model.lastup;
        detail.titleName = model.name;
        
    [self.navigationController pushViewController:detail animated:YES];
    }
}


@end
